<template>
  <div class="about-master-container">
    <base-breadcrumb :breadcrumb="!isAudit">
      <b-steps
        :current="stepVal"
        direction="vertical"
        @change.self="stepChange"
      >
        <b-step title="基本信息">
          <a-card
            v-show="activeKey[0]"
            slot="description"
            v-loading="loading"
            :bordered="false"
          >
            <a-form-model
              ref="ruleForm"
              :model="formData"
              :rules="rules"
            >
              <a-row>
                <a-col span="8">
                  <a-form-model-item
                    label="剩余物资处置申请编码"
                    prop="disposalApplyCode"
                  >
                    <a-input-search
                      v-model="formData.disposalApplyCode"
                      placeholder="请选择"
                      :disabled="state === 3"
                      @search="openDisposal"
                      @click="openDisposal"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="剩余物资调拨单编码">
                    <BaseInput
                      v-model="formData.code"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="编号"
                    prop="number"
                  >
                    <BaseInput
                      v-model="formData.number"
                      :disabled="state === 3"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col span="8">
                  <a-form-model-item
                    label="调出项目"
                    prop="transferOutOrgId"
                  >
                    <BaseInput
                      v-model="formData.ownerOrgName"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="调入项目"
                    prop="transferInOrgId"
                  >
                    <a-input-search
                      v-model="formData.allocatInOrgName"
                      placeholder="请选择"
                      :disabled="state === 3"
                      @search="openInOrg"
                      @click="openInOrg"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="接收人"
                    prop="recipientName"
                  >
                    <a-input-search
                      v-model="formData.recipientName"
                      placeholder="请选择"
                      :disabled="state === 3"
                      @search="openPerson"
                      @click="openPerson"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col span="8">
                  <a-form-model-item
                    label="日期"
                    prop="allocatDate"
                  >
                    <a-date-picker
                      v-model="formData.allocatDate"
                      value-format="YYYY-MM-DD"
                      :disabled="state === 3"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="金额合计（元）">
                    <BaseInput
                      v-model="formData.sumAmount"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="创建人">
                    <BaseInput
                      v-model="formData.creatorName"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col span="8">
                  <a-form-model-item label="创建时间">
                    <BaseInput
                      v-model="formData.createTime"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                v-if="state !== 3"
                type="primary"
                @click="temporaryStorage()"
              >
                保存草稿
              </a-button>
              <a-button
                type="primary"
                @click="temporaryStorage(true)"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="调拨明细">
          <a-card
            v-if="activeKey[1]"
            slot="description"
            :bordered="false"
          >
            <detail
              :id="formData.id"
              ref="detail"
              :state="state"
              :disposal-apply-id="formData.disposalApplyId"
            />
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                type="primary"
                @click="previous"
              >
                上一步
              </a-button>
              <a-button
                type="primary"
                @click="next"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="相关附件">
          <a-card
            v-if="activeKey[2]"
            slot="description"
            :bordered="false"
          >
            <u-table
              :upload-list="addFile"
              :delete-url="fileDel"
              :is-show="state !== 3"
              :list-url="fileList"
              :business-id="formData.id"
              business-code="MM01"
            />
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                type="primary"
                @click="previous"
              >
                上一步
              </a-button>
            </div>
          </a-card>
        </b-step>
      </b-steps>
      <div
        v-if="!isAudit"
        class="pub-header-btn page-btn-right-top"
      >
        <template v-if="state !== 3">
          <a-button
            type="primary"
            :loading="loading"
            @click="submit"
          >
            提交
          </a-button>
          <a-button
            type="primary"
            :loading="loading"
            @click="temporaryStorage"
          >
            保存
          </a-button>
        </template>
        <a-button
          v-checkVisibleInDetail
          @click="$close"
        >
          关闭
        </a-button>
      </div>
      <org-list
        ref="orgInList"
        :org-code="'PD'"
        @getOrg="getOrgIn"
      />
      <org-list
        ref="orgOutList"
        @getOrg="getOrgOut"
      />
      <person-list
        ref="personList"
        :other-data="{ rootOrgId: formData.transferInOrgId }"
        @getPerson="getPerson"
      />
      <disposal
        ref="disposal"
        :other-data="otherData"
        @getDisposal="getDisposal"
      />
      <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
    </base-breadcrumb>
  </div>
</template>

<script>
import detail from '../components/detail/detail'
import disposal from '../components/disposal/disposal'
import {
    transfersAdd,
    transfersEdit,
    audit,
    addFile,
    fileList,
    fileDel,
    transfersDetail
} from '@/api/material/remaining/transfers'
import { themeChoose } from '@/mixin/mixin'
// import project_person_list from '@/views/materials/remaining/transfers/components/project_person_list'

export default {
    // name:'a'+Date.now(),
    mixins: [themeChoose],
    components: {
        detail,
        disposal
        // project_person_list
    },
    props: {
        isAudit: {
            // 是否作为审批详情
            type: Boolean,
            default: false
        }
    },
    watch: {
        isAudit: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.state = 3
                }
            }
        },
        stepVal(newVal, oldVal) {
            this.$set(this.activeKey, newVal, true)
        }
    },
    data() {
        return {
            activeKey: [true, false, false, false, false, false, false],
            loading: false,
            state: Number(this.$route.query.state),
            isSubmit: false,
            otherData: { disposalMethodId: '623332127508926464' },
            row: this.$route.query.row,
            formData: {
                createTime: this.getNowTime(),
                creatorName: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name,
                disposalApplyCode: '',
                code: '',
                number: '',
                ownerOrgName: '',
                allocatInOrgName: '',
                recipientName: '',
                allocatDate: null,
                sumAmount: '',
                disposalApplyId: null,
                transferInOrgId: '',
                transferOutOrgId: '',
                recipientId: ''
            },
            isNext: false,
            allList: [],
            stepVal: 0,
            addFile: addFile(),
            fileDel: fileDel(),
            fileList: fileList(),
            rules: {
                disposalApplyCode: { required: true, message: '剩余物资处置申请编码不能为空', trigger: 'change' },
                number: { required: true, message: '编号不能为空', trigger: 'blur' },
                transferOutOrgId: { required: true, message: '调出单位不能为空', trigger: 'change' },
                transferInOrgId: { required: true, message: '调入单位不能为空', trigger: 'change' },
                recipientName: { required: true, message: '接收人不能为空', trigger: 'change' },
                allocatDate: { required: true, message: '日期不能为空', trigger: 'change' }
            },
            //获取流程配置值
            processConfig: null,
            //点击提交发送流程配置值
            setProcessConfig: null,
            businessId: null
        }
    },
    created: async function () {
        if (this.state !== 1) {
            this.formData.id = this.$route.query.id
            await this.getEditInfo()
            this.isSubmit = true
        }
         //获取通过获取流程配置值
        this.processConfig = await this.$getConfigFn('mm_surplus_transfer')
    },
    methods: {
        projectChange(val, type) {
            this.project.map((item) => {
                if (item.code === val) {
                    if (type === 1) {
                        this.formData.ownerOrgName = item.name
                        this.formData.transferOutOrgId = val
                    } else {
                        this.formData.allocatInOrgName = item.name
                        this.formData.transferInOrgId = val

                        this.formData.recipientName = ''
                        this.formData.recipientId = ''
                    }
                }
            })
        },
        openDisposal: function () {
            this.$refs.disposal.open()
        },
        getDisposal: function (row) {
            this.formData.disposalApplyCode = row.code
            this.formData.disposalApplyId = row.id
            this.formData.ownerOrgName = row.project
            this.formData.transferOutOrgId = row.projectId
        },
        openInOrg: function () {
            this.$refs.orgInList.open()
        },
        getOrgIn: function (row) {
            if (row.name === this.formData.ownerOrgName) {
                return this.$noticeWarning('调入项目和调出项目不能相同')
            }
            this.formData.allocatInOrgName = row.name
            this.formData.transferInOrgId = row.id
        },
        openOutOrg: function () {
            this.$refs.orgOutList.open()
        },
        getOrgOut: function (row) {
            this.formData.ownerOrgName = row.name
            this.formData.transferOutOrgId = row.id
        },
        getPerson: function (row) {
            this.formData.recipientName = row.employeeName
            this.formData.recipientId = row.employeeId
        },
        openPerson: function () {
            if (!this.formData.transferInOrgId) {
                this.$message.warning('请先选择调入项目')
                return
            }
            this.$refs.personList.open()
        },
        stepChange: function (val) {
            if (!this.formData.id && !this.isAudit) {
                if (val) {
                    this.$message.warning('切换步骤前请先填写基本信息')
                    this.stepVal = 0
                }
            } else {
                if (!this.isNext) {
                    this.$set(this.activeKey, val, !this.activeKey[val])
                }
            }
            this.isNext = false
        },
        next: function (val) {
            this.isNext = true
            this.stepVal++
        },
        previous: function () {
            this.isNext = true
            this.stepVal--
            if (this.stepVal < 0) {
                this.stepVal = 0
            }
        },
        // 获取编辑回显数据
        async getEditInfo() {
            this.loading = true
            let res = await transfersDetail({ id: this.formData.id })
            if (res.code === 200) {
                this.formData = this.$assign(this.formData, res.data)
            }
            this.loading = false
        },
        /**
         * @description: 校验表格
         */
        async checkTable(resolve, reject) {
            let list =
                (await new Promise((resolves, rejects) => {
                    this.$refs.detail?.getAll((res) => {
                        resolves(res.data)
                    })
                })) || []
            if (list.length === 0) {
                this.$noticeWarning('调拨明细表不能为空！')
                reject()
            }
            for (let index in list) {
                let page = Math.ceil((Number(index) + 1) / this.$refs.detail?.pageSize)
                let row = list[index]
                for (let key in this.$refs.detail?.rules) {
                    let value = this.$refs.detail?.rules[key]?.[0]
                    if (this.$isEmpty(row[key])) {
                        this.$noticeWarning(`《调拨明细表》第${page}页第${Number(index) + 1}行：${value.message}`)
                        reject()
                        return
                    }
                }
            }
            resolve()
        },
        submit() {
            this.setProcessConfig = null;
            if (this.isSubmit) {
                // 校验表格表单项
                new Promise((resolve, reject) => {
                    this.checkTable(resolve, reject)
                }).then(() => {
                    this.submitApprovalConfirm(this.isSubmit?this.processConfig:6, async(flag)=>{
                        if(!flag) {
                          this.loading = false
                          return
                        }
                        this.loading = true
                        let res = await audit({ baseId: this.formData.id, auditStatus: this.formData.auditStatus })
                        if (res.code === this.SUCCESS_CODE) {
                            this.$message.success('提交成功')
                            //提交时，返回id
                            this.businessId = this.formData.id;
                            this.setProcessConfig = this.processConfig;
                            //this.$router.push({ path: '/material/remaining/transfers' })
                        }
                        this.loading = false
                    })
                })
            } else {
                this.$message.warning('提交之前请先暂存')
            }
        },
        temporaryStorage(isNext) {
            if (this.state === 3) {
                this.next()
                return
            }
            this.$refs.ruleForm.validate(async (valid, object) => {
                if (valid) {
                    if (this.formData.transferInOrgId === this.formData.transferOutOrgId) {
                        this.$message.error('调入单位和调出单位不能相同')
                        return
                    }
                    this.loading = true
                    if (this.state === 2 || this.formData.id) {
                        let res = await transfersEdit(this.formData)
                        if (res.code === 200) {
                            this.$message.success('暂存成功')
                            this.isSubmit = true
                            if (isNext) {
                                this.next()
                            }
                        }
                    } else {
                        let res = await transfersAdd(this.formData)
                        if (res.code === 200) {
                            this.$message.success('暂存成功')
                            this.isSubmit = true
                            if (isNext) {
                                this.next()
                            }
                            this.formData.id = res.data.id
                            await this.getEditInfo()
                        }
                    }
                    this.loading = false
                } else {
                  this.$message.warning("请填写完所有必填项信息")
                    return false
                }
            })
        }
    }
}
</script>
